﻿using Microsoft.Extensions.DependencyInjection;
using QPlcPlayer.Models;
using QPlcPlayer.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QPlcPlayer
{
	public partial class SettingIPForm : Form
	{
		public static List<QCpuType> CPUTypes = new List<QCpuType>
		{
			new QCpuType{Name="S7200",Code=0},
			new QCpuType{Name="Logo0BA8",Code=1},
			new QCpuType{Name="S7200Smart",Code=2},
			new QCpuType{Name="S7300",Code=10},
			new QCpuType{Name="S7400",Code=20},
			new QCpuType{Name="S71200",Code=30},
			new QCpuType{Name="S71500",Code=40}
		};
		public static List<QDataType> DataTypes = new List<QDataType>
		{
			new QDataType{Name="BOOL",DataType=QDataTypeEnum.BOOL},
			new QDataType{Name="UNIT",DataType=QDataTypeEnum.UNIT},
			new QDataType{Name="USINT",DataType=QDataTypeEnum.USINT},
			new QDataType{Name="CHAR",DataType=QDataTypeEnum.CHAR},
			new QDataType{Name="DWORD",DataType=QDataTypeEnum.DWORD},
			new QDataType{Name="DINT",DataType=QDataTypeEnum.DINT},

		};
		public SettingIPForm()
		{
			InitializeComponent();

			InitSettingForm();
		}

		private void InitSettingForm()
		{
			this.CenterToParent();
			comboBox1.ValueMember = "Code";
			comboBox1.DisplayMember = "Name";
			comboBox1.Items.AddRange(CPUTypes.ToArray());

			var car = AppRuntime.GetService().GetService<AgvCarService>().GetAgvCarByNumber(AppRuntime.CarNumber) ?? new Models.AgvCar();
			if (car != null)
			{
				lblCarNumber.Text = car.CarNumber;
				txtIP.Text = car.IP;
				for (int i = 0; i < CPUTypes.Count; i++)
				{
					if (car.PlcType == CPUTypes[i].Code)
					{
						comboBox1.SelectedIndex = i;
						break;
					}
				}
			}



		}

		private void button2_Click(object sender, EventArgs e)
		{
			this.Close();
		}


		/// <summary>
		/// 保存数据至数据库
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void button1_Click(object sender, EventArgs e)
		{
			var carplc = new AgvCar
			{
				CarNumber = AppRuntime.CarNumber,
				IP = txtIP.Text.Trim(),

			};
			var cpuIndex = comboBox1.SelectedIndex;
			if (cpuIndex != -1)
			{
				carplc.PlcType= CPUTypes[cpuIndex].Code;
			}
			var res = AppRuntime.GetService().GetService<AgvCarService>().UpdateAgvCarPLC(carplc);
			if (res == false)
			{
				MessageBox.Show("保存失败");
				return;
			}
			if (MessageBox.Show("保存成功") == DialogResult.OK)
			{
				Task.Run(() =>
				{
					AppRuntime.UpdateData();
				});
				this.Close();
			}

		}
	}
}
